<template>
  <div>
    <el-dialog v-model="model" title="添加部门">
      <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="所属公司" prop="gs_id">
          <company-selector v-model="form.gs_id"/>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input type="text" v-model="form.name"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="model = false">取消</el-button>
          <el-button type="primary" @click="submitForm" v-loading="isLoading">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, useTemplateRef} from 'vue'
import type {DepartmentVO} from "../../../types";
import CompanySelector from "../../../components/CompanySelector.vue";
import {type FormRules, type FormInstance, ElMessage} from "element-plus"
import {insertDepartment} from "../../../api/department.ts";
import {useMutation} from "@pinia/colada";

const model = defineModel<boolean>()

const form = ref<DepartmentVO>({})
const formRef = useTemplateRef<FormInstance>('formRef')
const rules = reactive<FormRules<DepartmentVO>>({
  gs_id: [{
    required: true, message: '请选择所属公司'
  }],
  name: [{
    required: true, message: '请输入部门名称'
  }]
})

const emits = defineEmits<{
  success: []
}>();


const submitForm = async () => {
  await formRef.value?.validate((valid) => {
    if (valid) {
      insertDepartmentFn(form.value)
    }
  })
}

let {mutate: insertDepartmentFn, isLoading} = useMutation({
  mutation: (departmentVo: DepartmentVO) => insertDepartment(departmentVo),
  onSuccess: () => {
    // 隐藏弹窗
    model.value = false
    // 触发成功事件
    emits('success')
    formRef.value?.resetFields()
    ElMessage.success('添加成功')
  },
  onError: () => {
    ElMessage.error('添加失败')
  }
});
</script>

<style scoped>

</style>